import axios from '@/config/axios.config'
import $http from '@/config/$http.config'
import {getCookie, removeCookie} from '@/service/util.service'
import {getNetworkType} from "@/service/util.function";
import {
  LOGIN_SUCCESS,
  GET_USER_SUCCESS,
  GET_USER_FAILURE,
  SET_HTTP_HEADERS,
  SET_APP_ID,
  SET_PROJECT_ID,
  SET_PROJECT_NAME
} from '../mutation-types'

// state
let state = {
  'user': getCookie('user') && JSON.parse(getCookie('user')) || null,
  'guide': getCookie('guide') && JSON.parse(Number(getCookie('guide')) || 0) || 0,
  'app_id': 1,
  'project_id': 1,
  'project_name': '分发系统',
  'vip': getCookie('vip'),
  'timeEnd': getCookie('timeEnd'),
  'alertState': true,
};

// actions
const actions = {
  getUserInfo: ({commit, dispatch}) => {
    let user = getCookie('user');
    if (user) {
      commit('GET_USER_SUCCESS', JSON.parse(user));
      dispatch('SET_HTTP_HEADERS', JSON.parse(user).token);
    } else {
      commit('GET_USER_FAILURE');
      dispatch('SET_HTTP_HEADERS');
    }
  },
  // 设置HTTP请求头
  [SET_HTTP_HEADERS]: (_, payload) => {
    if (payload) {
      axios.defaults.headers['token'] = payload;
    }
  },
  loginSuccess: ({commit}, payload) => {
    commit(LOGIN_SUCCESS, payload);
  },
  setApp: ({commit}, payload) => {
    commit(SET_APP_ID, payload.app_id);
    commit(SET_PROJECT_ID, payload.project_id);
    commit(SET_PROJECT_NAME, payload.project_name);
  },
  dingtalk: ({commit}, payload) => {
    return false;
  },
};

// mutations
const mutations = {
  // 登陆成功
  [LOGIN_SUCCESS](state, payload) {
    state.user = payload;
  },
  // 用户信息获取成功
  [GET_USER_SUCCESS](state, payload) {
    state.user = payload;
  },
  // 用户信息获取失败
  [GET_USER_FAILURE](state) {
    state.user = null;
    removeCookie('user');
  },
  // 设置app_id
  [SET_APP_ID](state, payload) {
    state['app_id'] = payload;
  },
  // 设置project_id
  [SET_PROJECT_ID](state, payload) {
    state['project_id'] = payload;
  },
  // 设置project_name
  [SET_PROJECT_NAME](state, payload) {
    state['project_name'] = payload;
  }
};

// getters
const getters = {
  user: (state) => {
    return state.user
  }
};

export default {
  state,
  actions,
  mutations,
  getters
};
